import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Notification } from 'element-ui'
import { userHttp } from '@/api/user'
const state = {
  token: getToken(),  //用户登录信息
  name: '',   //用户姓名
  avatar: '',   //头像
  introduction: '',  //用户说明
  roles: [],     //角色数组
  roleId:'',    //角色id
  userName:'',   //用户名，工号
  btns:{},   //页面按钮权限集合
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERNAME(state, userName) {
    state.userName = userName
  },
  SET_ROLEID(state, roleId) {
    state.roleId = roleId
  },
  SET_BTNS: (state, btns) => {
    state.btns = btns
  },
}

const actions = {
	//查询页面按钮权限
	setPageBtns({commit,state},meta) { //获取角色并赋权
		return new Promise(async (resolve) => {
			userHttp.queryBtns(state.roleId,meta.moduleId).then(response => {
				let data =  response.result || []
				let obj = {}
				for(let i = 0; i < data.length; i++) {
					obj[data[i]] = true
				}
				let btns = state.btns
				btns[meta.moduleId] = obj
				commit('SET_BTNS',btns ) //状态管理保存角色数组
				resolve()
			})
		})
	},
	//存储roles
	setRoleId({commit}, roleId) {
		return new Promise(async resolve => {
			commit('SET_ROLEID', roleId) //状态管理保存角色数组
			resolve()
		})
	},
	getRoles({commit}) { //获取角色并赋权
		return new Promise(async (resolve,reject) => {
			userHttp.queryRoles().
			then(response => {
				const roles = response.result || []
				if(!roles || roles.length <= 0) {
					Notification({
						title: '提示',
						message: '当前用户角色信息不存在！',
						type: 'warning'
					})
					resolve(roles)
					return
				}
				commit('SET_ROLES', roles) //状态管理保存角色数组
				//显示默认角色
				let hasDefault = false
				for(let i = 0; i < roles.length; i++) {
					if(roles[i].isDefaultRole === "1") {
						commit('SET_ROLEID', roles[i].roleId)
						hasDefault = true
					}
				}
				//若没有默认角色，设置角色为第一个
				if(hasDefault === false) {
					commit('SET_ROLEID', roles[0].roleId)
				}
				resolve(roles)
			})
		})
	},
	getMenus({state}) { //从后台获取当前角色有权限的菜单列表
		return new Promise(async resolve => {
			userHttp.queryMenus(state.roleId).then(response => {
				const menus = response.result || []
				resolve(menus)
			})
		})
	},
	//设置用户名
	setUserName({commit}, userName) {
		return new Promise(async resolve => {
			commit('SET_USERNAME', userName)
			resolve()
		})
	},
	// 登陆后的处理
	login({commit}) {
		return new Promise(async (resolve) => {
			userHttp.checkLogin().then(response => {
				let data = response.result || {}
				sessionStorage.username = data.userName
				commit('SET_USERNAME', data.userName)
				commit('SET_TOKEN', `${data.userName}_token`)
				setToken( `${data.userName}_token`)
				resolve()
			})
		})
	},

	// 登出后的处理
	logout({commit,dispatch}) {
		return new Promise(async resolve => {
			commit('SET_TOKEN', '')
			commit('SET_ROLES', [])
			removeToken()
			resetRouter()
			// reset visited views and cached views
			dispatch('tagsView/delAllViews', null, {root: true})
			resolve()
		})

	},

	// 删除登录标识token
	resetToken({commit}) {
		return new Promise(async resolve => {
			commit('SET_TOKEN', '')
			commit('SET_ROLES', [])
			removeToken()
			resolve()
		})

	},

	// 切换角色后的操作
	changeRoles({dispatch}) {
		return new Promise(async () => {
			resetRouter()
			// reset visited views and cached views
			dispatch('tagsView/delAllViews', null, {root: true})
		})
	}
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
